package com.controller.lx;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.entity.Role;
import com.service.ServiceException;
import com.service.lx.RoleService;
import com.utils.RoleFunctionItem;
import com.utils.Result;

@Controller
public class RoleController {
	@Autowired
	private RoleService roleService;
	/**
	 * 分页查询角色
	 * @param curpage
	 * @param pagesize
	 * @return
	 */
	/**
	 * 查询用户
	 * @return
	 */
	@PostMapping("/role_select_")
	@ResponseBody
	public Page<Role> findAll(@RequestParam("field") String field, 
			@RequestParam("curpage") Integer curpage, 
			@RequestParam("pagesize") Integer pagesize){
		return roleService.findRoles(field, curpage, pagesize);
	}
	
	/**
	 * 添加/修改
	 * @param serve
	 * @throws ServiceException
	 */
	@PostMapping("/role_addandupdate_")
	@ResponseBody
	public Result addAndUpdate(@RequestBody Role role){
		roleService.addAndUpdateRole(role);;
		return Result.SUCCESS;
	}

	/**
	 * 逻辑删除
	 * @param Id
	 * @throws ServiceException
	 */
	@DeleteMapping("/role_ifdelete_")
	@ResponseBody
	public Result UpdateIfdelete(Long Id){
		roleService.UpdateFunctionIfdelete(Id);
		return Result.SUCCESS;
	}

	/**
	 * 批量删除
	 * @param qaIds
	 */
	@PostMapping("/role_delete_arr_")
	@ResponseBody
	public Result deletBatchRoles(@RequestBody JSONArray Ids) {
		roleService.deletArrIfDelete(JSONObject.parseArray(Ids.toString(), Long.class));
		return Result.SUCCESS;
	}
	
	/**
	 * 获取功能列表
	 * @param roleId
	 * @return
	 */
	@GetMapping("/role_getfunctions_")
	@ResponseBody
	public Map getFunctionsByRole(Long roleId) {
		List<RoleFunctionItem> all = roleService.queryAllFunctions();
		List<Long> special = roleService.getFunctionsByRole(roleId);
		Map map = new HashMap<>();
		map.put("all", all);
		map.put("special", special);
		return map;
	}
	
	/**
	 * 给角色授权
	 * @param map
	 */
	@PostMapping("/role_addfunctions_")
	@ResponseBody
	public Result grantForRole(@RequestBody Map map) {
		try {
			roleService.grantForRole(map);
			return Result.SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return Result.FAILURE("授权失败！");
		}
	}
}
